package cmd

import (
	"fmt"
	"os"
	"kscan/pkg/config"
	"kscan/pkg/scanner"

	"github.com/spf13/cobra"
)

var (
	cfgFile    string
	target     string
	pocDir     string
	threads    int
	timeout    int
	output     string
	verbose    bool
	proxyURL   string
)

var rootCmd = &cobra.Command{
	Use:   "kscan",
	Short: "一个功能强大的Web漏洞扫描器",
	Long: `KSCAN - 基于YAML POC的Web漏洞扫描器

支持功能:
  - 自定义YAML格式POC
  - 多线程并发扫描
  - 多种漏洞检测
  - 详细的扫描报告
  - 代理支持`,
	Run: func(cmd *cobra.Command, args []string) {
		runScan()
	},
}

func Execute() error {
	return rootCmd.Execute()
}

func init() {
	rootCmd.PersistentFlags().StringVarP(&target, "target", "t", "", "目标URL或URL列表文件")
	rootCmd.PersistentFlags().StringVarP(&pocDir, "poc", "p", "./pocs", "POC文件目录")
	rootCmd.PersistentFlags().IntVarP(&threads, "threads", "c", 10, "并发线程数")
	rootCmd.PersistentFlags().IntVar(&timeout, "timeout", 10, "HTTP请求超时时间(秒)")
	rootCmd.PersistentFlags().StringVarP(&output, "output", "o", "", "结果输出文件")
	rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "详细输出模式")
	rootCmd.PersistentFlags().StringVar(&proxyURL, "proxy", "", "代理URL (如: http://127.0.0.1:8080)")
	
	rootCmd.MarkPersistentFlagRequired("target")
}

func runScan() {
	// 创建配置
	cfg := &config.Config{
		Target:   target,
		PocDir:   pocDir,
		Threads:  threads,
		Timeout:  timeout,
		Output:   output,
		Verbose:  verbose,
		ProxyURL: proxyURL,
	}

	// 创建扫描器
	s, err := scanner.NewScanner(cfg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "初始化扫描器失败: %v\n", err)
		os.Exit(1)
	}

	// 执行扫描
	fmt.Println("开始扫描...")
	results, err := s.Scan()
	if err != nil {
		fmt.Fprintf(os.Stderr, "扫描失败: %v\n", err)
		os.Exit(1)
	}

	// 输出结果
	s.PrintResults(results)
	
	// 保存结果到文件
	if output != "" {
		if err := s.SaveResults(results, output); err != nil {
			fmt.Fprintf(os.Stderr, "保存结果失败: %v\n", err)
		}
	}
}